package com.etoak.utils;

import cn.hutool.json.JSONObject;
import com.etoak.bean.ResultVo;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class BaiDuApiUtil {
    /**
     * 获取百度云api密钥
     */
    @Value("${baiduapi.api-key}")
    public String API_KEY;
    @Value("${baiduapi.secret-key}")
    public String SECRET_KEY;

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public ResultVo examine(String text) throws IOException {
        try {
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "text=" + text);
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            System.out.println("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + getAccessToken());
            //接收返回的响应信息
            JSONObject resultJson = new JSONObject(response.body().string());
            //判断当前语句是否合规

            //不合规时，提示原由
            if (resultJson.getInt("conclusionType") == null) {
                return ResultVo.error(resultJson.getJSONArray("data")
                        .getJSONObject(0).getStr("msg"));
            }

            if (resultJson.getInt("conclusionType") == 1) {
                return ResultVo.success("该内容合规");
            }
            return ResultVo.error("该内容不合规");
        } catch (Exception e){
            e.printStackTrace();
            return ResultVo.error("该内容不合规");
        }
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    public String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getStr("access_token");
    }

}
